package com.ms.aspectj.normal;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @Aspect 使用除了要添加这个注解之外还需要添加@Component注解
* @Author ztd
*/
@Aspect
@Component
@Slf4j
public class AspectjAdvice {
    @Pointcut("execution(public * * (..))")
    public void pointCut() {

    }

    /**
     *
     * @param joinPoint
     */
    @Before("pointCut()")
    public void logStart(JoinPoint joinPoint){
        log.info("@Before args:{}", Arrays.asList(joinPoint.getArgs()));
    }

    @After("pointCut()")
    public void logEnd(JoinPoint joinPoint){
        log.info("@After args:{}", Arrays.asList(joinPoint.getArgs()));
    }

    /**
     * JoinPoint一定要出现在参数表的第一位
     * @param joinPoint
     * @param result
     */
    @AfterReturning(value="pointCut()",returning="result")
    public void logReturn(JoinPoint joinPoint,Object result){
        log.info("====@AfterReturning====");
        log.info("@AfterReturning method name:->{}", joinPoint.getSignature().getName());
        log.info("@AfterReturning result:{}", result);
    }

    @AfterThrowing(value="pointCut()",throwing="exception")
    public void logException(JoinPoint joinPoint,Exception exception){
        log.info("@AfterThrowing method name:->{}", joinPoint.getSignature().getName());
        if (exception instanceof MyException) {
            log.info("报MyException错误了:{}", exception);
        } else if(exception instanceof ArithmeticException) {
            log.info("报ArithmeticException错误了:{}", exception);
        }
    }

}
